package com.tre.jdevtemplateboot.common.jwt.impl;

import com.tre.jdevtemplateboot.common.dto.PropertiesConfig;
import com.tre.jdevtemplateboot.common.jwt.IJwtTokenManagerService;
import com.tre.jdevtemplateboot.common.util.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.impl.DefaultClaims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author JDev
 */
@Service
public class JwtTokenManagerServiceImpl implements IJwtTokenManagerService {

    @Autowired
    private PropertiesConfig propertiesConfig;

    @Override
    public String generateToken(String id) {
        Claims claims = new DefaultClaims();
        claims.setId(id);
        return JwtUtils.createJwtToken(claims);
    }


    @Override
    public String generateRefreshToken(String id) {
        Claims claims = new DefaultClaims();
        claims.setId(id);
        return JwtUtils.createJwtToken(claims, Long.parseLong(propertiesConfig.getRefreshTokenExpire()));
    }

    @Override
    public String updateToken(String token) {
        Claims claims = JwtUtils.getClaimsByToken(token);
        String id = claims.getId();
        Long expiration = Long.parseLong(propertiesConfig.getTokenExpire());
        if (expiration > 0) {
            return generateToken(id);
        }
        return token;
    }

}
